<?php

require_once('../const.php');
require_once('../includes/utilities.php');

/**
 * This class is contains all of the utility methods that are
 * useful to the models.
 * 
 * @author Matt Makins
 * 
 */
abstract class BaseModel{
	
	protected static $errors = array();
		
	/**
	 * use to validate form input, if a form element is empty
	 * the method returns false and an error message is added to 
	 * the errors array
	 * 
	 * @param unlimited amount of params can be checked
	 * @return boolean
	 */
	protected static function validate_presence_of(){
	
		$args = func_num_args();
		$empty = 0;
		
		for($i=0;$i<$args;$i++){

			$input = func_get_arg($i);
			$field = func_get_arg($i);
			// handles FormItem objects, allows us to get the
			// field name of the form item for error messaging 
			// purposes
			if(get_class(func_get_arg($i)) == "FormItem"){
				$input = func_get_arg($i)->getValue();
				$field = func_get_arg($i)->getField();
			}			
			// this is required because a input that only contains html
			// with no text content is also empty
			$input = Utilities::stripTagsandWhitespace($input);

			if(empty($input)){
				array_push(self::$errors, $field . " is empty!");				
				$empty++;
			}
		}
		if($empty > 0){
			return false;
		}
		return true;
	}
	
	/**
	 * use to validate the uniqueness of a field in a specified
	 * db table
	 * 
	 * @param item to be validated
	 * @param name of db table
	 * @return boolean
	 */
	protected function validate_uniqueness_of($item, $table){
		
		if($table=="category"){
			self::connect();
			$find = mysql_query("SELECT * FROM category");
			while($row = mysql_fetch_array($find)){
				// using ltrim and rtrim because row['name'] was longer than should be
				// must have been prefixed/postfixed with white space in db
				if(ltrim(rtrim($row['name'])) === $item)
					return false;					
			}
		}
		return true;
	}
	
	/**
	 * connects to the database
	 */
	protected static function connect(){
		$db= mysql_connect ("localhost", DBUSERNAME, DBPASSWORD) or die ('I cannot connect to the database because: ' . mysql_error());
    	mysql_select_db (DBNAME);
	}

	/**
	 * returns a list of current errors
	 * 
	 * @return array of errors
	 */	
	public static function getErrors(){
		return self::$errors;
	}
	
	/**
	 * clears the errors array
	 */
	public static function clearErrors(){
		for($i=0;$i<count(self::$errors);$i++){
			array_pop(self::$errors);
		}
	}
	
	/**
	 * returns the number of errors present
	 * 
	 * @return number of errors
	 */
	public static function getNumberOfErrors(){
		return count(self::$errors);
	}
	
}
?>
